/* 先把对应css和js文件删除 */
var fs = require('fs');
var stat = fs.stat;
var path = require('path');
var dest_css_path = 'F:\\lamp\\www\\xinkuai.com\\frontendsite\\static\\sdkios\\v10\\css';
var dest_js_path = 'F:\\lamp\\www\\xinkuai.com\\frontendsite\\static\\sdkios\\v10\\js';
var dest_php_path = 'F:\\lamp\\www\\xinkuai.com\\ApplicationFE\\Common\\viewphp\\sdkiosv10\\index.php';

var current_css_path = path.resolve(__dirname) + '\\static\\sdkios\\v10\\css';
var current_js_path = path.resolve(__dirname) + '\\static\\sdkios\\v10\\js';

function deleteFile(path) {
	var files = [];
	if (fs.existsSync(path)) {
		files = fs.readdirSync(path);
		files.forEach(function (file, index) {
			try {
				var curPath = path + '/' + file;
				fs.unlinkSync(curPath);
				console.log('删除' + curPath + '文件成功！')
			} catch (err) {
				console.err(err)
			}
		})
	}
}

deleteFile(dest_css_path)
deleteFile(dest_js_path)

/* 复制js和css到指定文件夹 */

function copyFile(src, dst) {
	fs.readdir(src, function (err, paths) {
		if (err) {
			throw err;
		}
		paths.forEach(function (path) {
			var _src = src + '\\' + path,
				_dst = dst + '\\' + path,
				readable, writeable;
			stat(_src, function (err, st) {
				if (err) {
					throw err;
				}
				if (st.isFile()) {
					try {
						readable = fs.createReadStream(_src);
						writeable = fs.createWriteStream(_dst);
						readable.pipe(writeable);
						console.log('复制文件' + _src + '到' + _dst + '成功！')
					} catch (err) {
						console.err(err);
					}

				}
			})
		})
	})
}
copyFile(current_css_path, dest_css_path);
copyFile(current_js_path, dest_js_path);

// 替换php css js文件

var sourceMap = require('./source-map.json')

function replaceFile(file) {
	console.log('开始替换php文件');
	try {
		fs.readFile(file, 'utf8', function (err, files) {
			var re;
			var manifest = /\<script.*(\/manifest\.?.*?js)/gi.exec(files)[1];
			var vendor = /\<script.*(\/vendor\.?.*?js)/gi.exec(files)[1];
			var appJS = /\<script.*(\/app\.?.*?js)/gi.exec(files)[1];
			var appCss = /\<link.*(\/app\.?.*?css)/gi.exec(files)[1];

			var newM = /(\/manifest.*\.js)/gi.exec(sourceMap['manifest']['js'])[1];
			var newV = /(\/vendor.*\.js)/gi.exec(sourceMap['vendor']['js'])[1];
			var newAppJS = /(\/app.*\.js)/gi.exec(sourceMap['app']['js'])[1];
			var newAppCss = /(\/app.*\.css)/gi.exec(sourceMap['app']['css'])[1];

			re = files.replace(manifest, newM)
			re = re.replace(vendor, newV)
			re = re.replace(appJS, newAppJS)
            re = re.replace(appCss, newAppCss)

			console.log(manifest + '被替换成' + newM)
			console.log(vendor + '被替换成' + newV)
			console.log(appJS + '被替换成' + newAppJS)
			console.log(appCss + '被替换成' + newAppCss)
			fs.writeFile(file, re, 'utf8', function (err) {
				if (err) return console.log(err);
				console.log('php替换成功！累死我鲁！')
			});
		})
	} catch (e) {
		console.err('process failed');
		console.err(e);
	}

}
replaceFile(dest_php_path)
